package com.woniu.util;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;


/**
 * @author 李桢
 * @date 2021/4/2 14:04
 */
@Component
public class JwtVerifyUtils {

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 私钥密码，保存在服务器，客户端是不会直到密码的，以防止被攻击*
     */
    private static final String SECRET = "mysecret";


    /**
     * 加密方式*
     */
    private static final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;


    /**
     * 对私钥进行加密*
     */
    private static Key getkey() {
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        return new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    }

    /**获取用户名**/
    public static String getUsername(String token) {
        Claims body = null;
        try {
            body = Jwts.parser().setSigningKey(getkey()).parseClaimsJws(token).getBody();
        } catch (SignatureException e) {
            throw new RuntimeException(e);
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("超时", e);
        } catch (Exception e) {
            throw new RuntimeException("未知错误", e);
        }
        return (String) body.get("userName");
    }

    /*** 解密Token查看其是否合法*/
    public boolean verifyToken(String token) {
        Claims body = null;
        try {
            body = Jwts.parser().setSigningKey(getkey()).parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        if (body == null) {
            return false;
        }

        //若不等于null，则去redis数据库查询token是否还存在，不存在则证明已经登出，不能放行
        String username = getUsername(token);

        return redisTemplate.hasKey(username);

    }
}
